const gulp = require("gulp");
const GulpSSH = require("gulp-ssh");
const fs = require("fs");

const host =["120.26.80.19"]
// 需要上传到服务器的路径
const uploadData = [];
const shellData = [];
host.map((item) => {
  const config = {
    ssh: {
      host: item,
      port: 22,
      username: "root",
      password: "Becauseofyou10",
    },
  };
  const gulpSSH = new GulpSSH({
    ignoreErrors: false,
    sshConfig: config.ssh,
  });
  function name() {
    return gulp
      .src(`./dist/**`)
      .pipe(gulpSSH.dest('/mnt/taro/'))
  }
  function shell(type) {
    return gulpSSH.shell(`rm -rf /mnt/taro/assets/**${type}**`);
  }
  shellData.push(shell);
  uploadData.push(name);
});
// 不删除服务器代码 单上传
gulp.task("deploy", gulp.series(...uploadData));
// 删除服务器中上上个版本的代码
// VITE_VERSON_CURRENT_TYPE是打包后要上传到服务器的尾缀一部分
// VITE_VERSON_TYPE 前三个是服务器上的版本 最后一个是当前上传到服务器的索引
function getDetail(cd) {
  const path = `./.env.${process.env.NODE_ENV}`;
  // 获取环境变量文件内容
  fs.readFile(path, { encoding: "utf-8", flag: "r" }, (err, data) => {
    const process = data.split("\r\n");
    const versionTypeIndex = process.findIndex((item) => {
      return item.includes("VITE_VERSON_TYPE");
    });
    let VITE_VERSON_TYPE = process.splice(versionTypeIndex, 1);
    const VITE_VERSON_TYPEIndex = process.findIndex((item) => {
      return item.includes("VITE_VERSON_CURRENT_TYPE");
    });
    process.splice(VITE_VERSON_TYPEIndex, 1);
    let dataed = VITE_VERSON_TYPE[0].split("=")[1].split(",");
    let currentIndex = VITE_VERSON_TYPE[0].split("=")[1].split(",")[3];
    shellData.map((item) => {
      item( dataed[currentIndex === 2 ? 0 : Number(currentIndex) + 1]);
    });
    dataed[currentIndex === 2 ? 0 : Number(currentIndex) + 1] =
      new Date().getTime();
    dataed[3] = [currentIndex === 2 ? 0 : Number(currentIndex) + 1];
    process.push(
      `VITE_VERSON_CURRENT_TYPE=${
        dataed[currentIndex === 2 ? 0 : Number(currentIndex) + 1]
      }`
    );
    process.push(`VITE_VERSON_TYPE=${dataed.join(",")}`);
    let str = "";
    process.map((item) => {
      if (item) str += item + "\r\n";
    });
    fs.writeFile(path, str, { encoding: "utf-8", flag: "w+" }, (err) => {});
  });
  cd();
}
// 先上传代码 再删除上上个版本的代码
gulp.task("deploy1", gulp.series(...uploadData, getDetail));
gulp.task("deploy2", gulp.series(...shellData,...uploadData));
